package com.longcai.service.impl.messagepush;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.Joiner;
import com.longcai.advice.RollBackExecption;
import com.longcai.bean.ApiResult;
import com.longcai.bean.DateUtil;
import com.longcai.bean.PageHelper;
import com.longcai.constants.BaseConstants;
import com.longcai.entity.customer.ClyjUser;
import com.longcai.entity.messagepush.ClyjMessagePush;
import com.longcai.entity.messagepush.ClyjMessagePushFormwordDesc;
import com.longcai.mapper.clyjuser.ClyjUserMapper;
import com.longcai.mapper.messagepush.ClyjMessagePushMapper;
import com.longcai.page.table.PageTableResponse;
import com.longcai.service.messagepush.ClyjMessagePushService;
import com.longcai.util.StringUtils;
import com.longcai.util.wechat.SendMessagePush;
import com.longcai.util.wechat.TemplateData;
import com.longcai.util.wechat.WX_UserUtil;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

import javax.transaction.RollbackException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 平台管理---消息推送 服务实现类
 * </p>
 *
 * @author kh
 * @since 2019-05-08
 */
@Service
public class ClyjMessagePushServiceImpl extends ServiceImpl<ClyjMessagePushMapper, ClyjMessagePush> implements ClyjMessagePushService {

	
	private static Logger logger = LoggerFactory.getLogger(ClyjMessagePushServiceImpl.class);
	@Autowired
	private ClyjMessagePushMapper  clyjMessagePushMapper;
	@Autowired
	private ClyjUserMapper  clyjUserMapper;
	
	/****
	 * 保存为草稿
	 * @throws RollBackExecption 
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public ApiResult<?> saveMessagePush(ClyjMessagePush clyjMessagePush,ClyjMessagePushFormwordDesc pushDesc) throws RollBackExecption {
		ApiResult<?> r=checkParam(clyjMessagePush);
		if(!r.getCode().equals(BaseConstants.SUCCESS)){
			return r;
		}
		try {
		clyjMessagePush.setMessagePushId(UUID.randomUUID().toString().replace("-", ""));
		clyjMessagePush.setCreateTime(LocalDateTime.now());
		clyjMessagePush.setMessageTitle(clyjMessagePush.getMessageTitle());
		clyjMessagePush.setWxFormworkId(clyjMessagePush.getWxFormworkId());
		String pushUserType = Joiner.on(",").join(clyjMessagePush.getPushUserTypeList()); 
		clyjMessagePush.setPushUserType(pushUserType);
		//(0,已发送 1，草稿)
		clyjMessagePush.setState("1");
		String wxCode = pushDesc.getWxCode();
		if(wxCode!=null && !wxCode.equals("")){
			JSONObject json =new JSONObject();
			String[] code = wxCode.split(",");
			String wxValue = pushDesc.getValue();
			String[] value = wxValue.split(",");
			for (int i=0;i<code.length;i++) {
				json.put(code[i], new TemplateData(value[i]==null?"":value[i],"#EE0000"));
			}
			clyjMessagePush.setContent(json.toJSONString());
		}
		
		Integer j = this.clyjMessagePushMapper.insert(clyjMessagePush);
		if(j==0){
			int a=1/j;
		}
		} catch (Exception e) {
			throw new RollBackExecption("消息推送保存草稿失败");
		}
		return ApiResult.success();
		
	}
	/**参数校验**/
	public ApiResult<?> checkParam(ClyjMessagePush clyjMessagePush){
		String messageTitle=clyjMessagePush.getMessageTitle();//推送标题
		String wxFormworkId =clyjMessagePush.getWxFormworkId();//微信模板id
		List<String> pushUserTypeList=clyjMessagePush.getPushUserTypeList();//推送用户(0会员,1,导购 2,讲师 3,经理, 4 商家) 前台数字接收list
		String type=clyjMessagePush.getState();//0 立即推送      1保存为草稿
		if(StringUtils.isEmpty(wxFormworkId)||StringUtils.isEmpty(type)
				||pushUserTypeList==null||pushUserTypeList.size()<1){
			logger.error("推送参数非法"+"-------------------"
								+"messageTitle"+messageTitle+"-------------------"
								+"wxFormworkId"+wxFormworkId+"-------------------"
								+"type"+type+"-------------------"
								+"pushUserTypeList"+pushUserTypeList+"-------------------"
					
					);
			return ApiResult.fail("消息推送参数非法");
		}
		return ApiResult.success();
	}
	
	/****
	 * 立即推送
	 * @throws RollBackExecption 
	 * @throws RollbackException 
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public ApiResult<?> immediatelyPush(ClyjMessagePush clyjMessagePush,ClyjMessagePushFormwordDesc pushDesc) throws RollBackExecption, RollbackException {
		/**1.参数校验**/
		ApiResult<?> r=checkParam(clyjMessagePush);
		if(!r.getCode().equals(BaseConstants.SUCCESS)){
			return r;
		}
		String messagePushId=clyjMessagePush.getMessagePushId();//消息推送id
		/**2.微信消息推送信息拼接**/
		JSONObject json =new JSONObject();
		for (ClyjMessagePushFormwordDesc formwordDesc : clyjMessagePush.getClyjMessagePushFormwordDescList()) {
	        json.put(formwordDesc.getWxCode(), new TemplateData(formwordDesc.getValue(),"#EE0000"));
		}
		/**** 推送用户(0会员,1,导购 2,讲师 3,经理, 4 商家)前台数字接收list**/
		List<String> pushUserTypeList=clyjMessagePush.getPushUserTypeList();
		/**3.条件筛查要推送的用户**/
		QueryWrapper<ClyjUser> queryWrapper = new QueryWrapper<ClyjUser>();
		Boolean b=pushUserTypeList.contains("4");//推送用户(0会员,1,导购 2,讲师 3,经理, 4 商家) 前台数字接收list
		if(b){
			queryWrapper.eq("ismich", "1").or().in("level",pushUserTypeList );//'是否店铺（1：是；2：否）',
		}else{
			queryWrapper.in("level", clyjMessagePush.getPushUserTypeList());
		}
		int c=0;//未关注本公众号人数
		int d=0;//关注本公众号并推送成功的人数
		List<ClyjUser> userList=clyjUserMapper.selectList(queryWrapper);
		if(userList==null||userList.size()<1){
			return ApiResult.fail("未查询到用户,微信消息推送失败");
		}
		for (int i = 0; i < userList.size(); i++) {
			String openid=userList.get(i).getOpenid();
			if(StringUtils.isNotEmpty(openid)){
			try {
				Integer j=WX_UserUtil.subscribeState(openid);
				if(j==0){
					logger.error("用户"+userList.get(i).getUsername()+"未关注本公众号,微信消息推送失败"
				    +"openid:"+openid+"---------------"
				    +"clyjUser:"+userList.get(i).toString()+"---------------"
					);
					c++;
					continue;
				}
			} catch (Exception e) {
				throw new RollbackException("校验用户否订阅该公众号失败");
			}
			try {
				SendMessagePush sendMessagePush= new SendMessagePush();
				ApiResult<?> rs=sendMessagePush.sendMessagePush(openid, clyjMessagePush.getWxFormworkId(), BaseConstants.MEESSAGE_PUSH_SKIP_URL, json,BaseConstants.MEESSAGE_PUSH_COLOUR);
				if(!rs.getCode().equals(BaseConstants.SUCCESS)){
					return ApiResult.fail("消息推送失败");
				}
				d++;
			} catch (Exception e) {
				return ApiResult.fail("发起微信消息推送失败");
			}
			}
			continue;
		}
		if(c==userList.size()){
			return ApiResult.fail("用户未关注本公众号,微信消息推送失败");
		}
		logger.info("消息推送------"+"未关注本公众号人数："+c);
		logger.info("消息推送------"+"关注本公众号并推送成功的人数："+d);
		try {
		/**保存推送信息**/
		if(messagePushId==null){
			clyjMessagePush.setMessagePushId(UUID.randomUUID().toString().replace("-", ""));
			clyjMessagePush.setCreateTime(LocalDateTime.now());
			clyjMessagePush.setMessageTitle(clyjMessagePush.getMessageTitle());
			clyjMessagePush.setWxFormworkId(clyjMessagePush.getWxFormworkId());
			String pushUserType = Joiner.on(",").join(clyjMessagePush.getPushUserTypeList()); 
			clyjMessagePush.setPushUserType(pushUserType);
			clyjMessagePush.setState("0");
			clyjMessagePush.setPushTime(LocalDateTime.now());
			clyjMessagePush.setContent(json.toJSONString());
			int i = this.clyjMessagePushMapper.insert(clyjMessagePush);
			if(i==0){
				logger.error("立即推送保存失败");
				int a=1/i;
			}
		}else {
			clyjMessagePush.setState("0");
			clyjMessagePush.setPushTime(LocalDateTime.now());
			int i=	this.clyjMessagePushMapper.updateById(clyjMessagePush);
			if(i==0){
				logger.error("更新推送信息失败");
				int a=1/i;
			}
		}
		} catch (Exception e) {
			throw new RollBackExecption("立即推送保存失败");
		}
		return ApiResult.success();
	}

	@Override
	public PageTableResponse messagePushList(ClyjMessagePush clyjMessagePush, PageHelper pageHelper) {
		 //分页
        Page<ClyjMessagePush> page = new Page<ClyjMessagePush>(pageHelper.getStart(), pageHelper.getLength());
        QueryWrapper<ClyjMessagePush> queryWrapper = new QueryWrapper<>();		
        if(StringUtils.isNotEmpty(clyjMessagePush.getMessageTitle())){
        	queryWrapper.like("message_title", clyjMessagePush.getMessageTitle());
        }
        if(StringUtils.isNotEmpty(clyjMessagePush.getMessagePushId())){
        	queryWrapper.eq("message_push_id", clyjMessagePush.getMessagePushId());
        }
        String date = DateUtil.formatDate(LocalDateTime.now(), "yyyy-MM-dd HH:mm:ss","");
        LocalDateTime leftTime=clyjMessagePush.getLeftTime();
        LocalDateTime rightTime=clyjMessagePush.getRightTime();
        if(leftTime!=null&&!leftTime.equals("")){
        	queryWrapper.between("create_time", leftTime, date);
        }
        if(rightTime!=null&&!rightTime.equals("")){
        	queryWrapper.between("create_time", leftTime, date);
        }
        if(leftTime!=null&&!leftTime.equals("")&&rightTime!=null&&!rightTime.equals("")){
        	queryWrapper.between("create_time", leftTime, rightTime);
        }
        IPage<ClyjMessagePush>  messagePushIPage= clyjMessagePushMapper.selectPage(page, queryWrapper);
        PageTableResponse sysRoleIPage = new PageTableResponse(messagePushIPage.getTotal(),
        		messagePushIPage.getTotal(), messagePushIPage.getRecords());
        return sysRoleIPage;
	}

}